package com.keter.dtx.controller;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.keter.dtx.service.AccountService;
import com.keter.dtx.service.OrderService;
import com.keter.dtx.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author jimin.jm@alibaba-inc.com
 * @date 2019/06/14
 */
@RestController
public class ATController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private StorageService storageService;

    @RequestMapping(value = "/reduce/{userId}/{money}", produces = "application/json")
    public Boolean debit(@PathVariable String userId, @PathVariable int money) {
        accountService.reduce(userId, money);
        return true;
    }

    @GetMapping(value = "/create/{userId}/{commodityCode}/{count}", produces = "application/json")
    public Boolean create(@PathVariable String userId, @PathVariable String commodityCode, @PathVariable Integer count) {
        orderService.create(userId, commodityCode, count);
        return true;
    }

    @RequestMapping(value = "/deduct/{commodityCode}/{count}", produces = "application/json")
    public Boolean deduct(@PathVariable String commodityCode,@PathVariable Integer count) {
        storageService.deduct(commodityCode, count);
        return true;
    }

    @RequestMapping(value = "/validate")
    @ResponseBody
    public Boolean validate(String name) {
        Record account = Db.findFirst("select * from account_tbl where user_id='U100000'");
        if (Integer.parseInt(account.get("money").toString()) < 0) {
            return false;
        }
        Record storage  = Db.findFirst("select * from storage_tbl where commodity_code='C100000'");
        if (Integer.parseInt(storage.get("count").toString()) < 0) {
            return false;
        }
        return true;
    }
}
